<?php

/*
 * Copyright 2008 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#namespace tehframework\validation;

/**
 * Utility class offering convenient methods for invoking a {@link Validator}
 * and for rejecting empty fields.
 * 
 * Checks for an empty field in {@link Validator} implementations can become
 * one-liners when using {@link rejectIfEmpty()} or
 * {@link rejectIfEmptyOrWhitespace()}.
 * 
 * @see Validator
 * @see ValidationErrors
 */
class ValidationUtils
{
	const EMPTY_ERROR_CODE = 'empty';
	
	const NOT_STRING_ERROR_CODE = 'type.string';
	
	/**
	 * Invoke the given {@link Validator} for the supplied object and
	 * {@link ValidationErrors} instance.
	 * 
	 * @param  Validator $validator
	 *         The Validator to be invoked.
	 * @param  mixed $obj
	 *         The object to bind the parameters to.
	 * @param  ValidationErrors $errors
	 *         The {@link ValidationErrors} instance that should
	 *         store the errors.
	 * @return bool
	 *         TRUE if the number of errors after invoking the validator did not
	 *         change; otherwise, FALSE.
	 * @throws IllegalArgumentException
	 *         If the supplied Validator does not
	 *         {@link Validator::supports() support} the validation
	 *         of the supplied object's type.
	 */
	public function invokeValidator(
		Validator $validator, $obj, ValidationErrors $errors)
	{
		if (($obj !== null) && !$validator->supports($obj))
		{
			throw new IllegalArgumentException(sprintf(
				'Validator [%s] does not support [%s].',
				get_class($validator),
				is_object($obj) ? get_class($obj) : gettype($obj)
			));
		}
		
		$errorCount = $errors->getErrorCount();
		
		$validator->validate($obj, $errors);
		
		return $errorCount === $errors->getErrorCount();
	}

	/**
	 * Reject the given field with the given error code, error arguments
	 * and default message if the value is empty.
	 * 
	 * An 'empty' value in this context means either NULL, the empty string "",
	 * array() or an instance of Countable if call to count() method returns 0.
	 * 
	 * The object whose field is being validated does not need to be passed
	 * in because the {@link ValidationErrors} instance can resolve field
	 * values by itself (it will usually hold an internal reference to the
	 * target object).
	 * 
	 * @param  ValidationErrors $errors
	 *         The ValidationErrors instance to register errors on.
	 * @param  string $field
	 *         The field name to check.
	 * @param  string $errorCode
	 *         The error code, interpretable as message key.
	 * @param  array? $errorArgs
	 *         The error arguments.
	 * @param  string? $defaultMessage
	 *         Fallback default message.
	 * @return ValidationUtils
	 */
	public function rejectIfEmpty(
		ValidationErrors $errors,
		$field,
		$errorCode = self::EMPTY_ERROR_CODE,
		array $errorArgs = null,
		$defaultMessage = null)
	{
		$value = $errors->getFieldValue($field);
		$empty = false;
		
		switch (gettype($value))
		{
			case 'null':
				$empty = true;
				break;
			
			case 'array':
				$empty = empty($value);
				break;
			
			case 'string':
				$empty = $value === '';
				break;
			
			case 'object':
				if ($value instanceof Countable)
				{
					$empty = count($value) === 0;
				}
				break;
		}
		
		if ($empty)
		{
			$errors->rejectValue($field, $errorCode, $errorArgs, $defaultMessage);
		}
		
		return $this;
	}

	/**
	 * Reject the given field with the given error code, error arguments
	 * and default message if the value is empty or just contains whitespace.
	 * 
	 * An 'empty' value in this context means either NULL, the empty string ""
	 * (or consisting wholly of whitespace), array() or an instance of Countable
	 * if call to count() method returns 0.
	 * 
	 * The object whose field is being validated does not need to be passed
	 * in because the {@link ValidationErrors} instance can resolve field
	 * values by itself (it will usually hold an internal reference to the
	 * target object).
	 * 
	 * @param  ValidationErrors $errors
	 *         The ValidationErrors instance to register errors on.
	 * @param  string $field
	 *         The field name to check.
	 * @param  string $errorCode
	 *         The error code, interpretable as message key.
	 * @param  array? $errorArgs
	 *         The error arguments.
	 * @param  string? $defaultMessage
	 *         Fallback default message.
	 * @return ValidationUtils
	 */
	public function rejectIfEmptyOrWhitespace(
		ValidationErrors $errors,
		$field,
		$errorCode = self::EMPTY_ERROR_CODE,
		array $errorArgs = null,
		$defaultMessage = null)
	{
		$value = $errors->getFieldValue($field);
		$empty = false;
		
		switch (gettype($value))
		{
			case 'null':
				$empty = true;
				break;
			
			case 'array':
				$empty = empty($value);
				break;
			
			case 'string':
				$empty = trim($value) === '';
				break;
			
			case 'object':
				if ($value instanceof Countable)
				{
					$empty = count($value) === 0;
				}
				break;
		}
		
		if ($empty)
		{
			$errors->rejectValue($field, $errorCode, $errorArgs, $defaultMessage);
		}
		
		return $this;
	}

	/**
	 * Reject the given field with the given error code, error arguments
	 * and default message if the value is not a string.
	 *
	 * The object whose field is being validated does not need to be passed
	 * in because the {@link ValidationErrors} instance can resolve field
	 * values by itself (it will usually hold an internal reference to the
	 * target object).
	 *
	 * @param  ValidationErrors $errors
	 *         The ValidationErrors instance to register errors on.
	 * @param  string $field
	 *         The field name to check.
	 * @param  string $errorCode
	 *         The error code, interpretable as message key.
	 * @param  array? $errorArgs
	 *         The error arguments.
	 * @param  string? $defaultMessage
	 *         Fallback default message.
	 * @return ValidationUtils
	 */
	public function rejectIfNotString(
		ValidationErrors $errors,
		$field,
		$errorCode = self::NOT_STRING_ERROR_CODE,
		array $errorArgs = null,
		$defaultMessage = null)
	{
		$value = $errors->getFieldValue($field);
		$type  = gettype($value);

		if (($type === 'string')
		|| (($type === 'object') && method_exists($value, '__toString')))
		{
			return $this;
		}
		
		$errors->rejectValue($field, $errorCode, $errorArgs, $defaultMessage);
		
		return $this;
	}
}